package com.ymatou.iapi.optrade.testcase;

import java.math.BigDecimal;

import org.joda.time.DateTime;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.req.AgreeRefundReq;
import com.ymatou.iapi.optrade.parameter.req.ApplyRefundReq;
import com.ymatou.iapi.optrade.parameter.vo.SalesRefundInfoVo;
import com.ymatou.iapi.optrade.resp.Order;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.optrade.service.AgreeRefundCall;
import com.ymatou.iapi.optrade.service.AutoConfirmReceiveCall;
import com.ymatou.iapi.optrade.service.RefundService;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.PayGateWayCallService;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.YMTTrading.TradingPlaceOrderCallService;
import com.ymttest.database.sharding.db.sharding.model.AutoReceiveOptPo;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;

/**
 * 自动确认收货 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_AutoConfirmReceive {

	private static AutoConfirmReceiveCall confirmreceivecall;
	private static AgreeRefundReq salesrefundsuccessReq = new AgreeRefundReq();
	private static AgreeRefundCall salesrefundsuccessCall = new AgreeRefundCall();

	private static OrderShardingWapper orderShardingWapper = new OrderShardingWapper();

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("买家自动确认收货");
	}

	@Before
	public void caseUp() {

		confirmreceivecall = new AutoConfirmReceiveCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(confirmreceivecall.getOpurl());
		orderShardingWapper.activeDeadCommunicationsLink(orderShardingWapper);
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_AutoConfirmReceive_001() {
		Logger.start(true, "自动确认收货成功");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
					.placeOrderWithLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();

			long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

			long userId = placeOrderResp.getUserId();

			long tradingId = placeOrderResp.getTradingId();

			BigDecimal useAccountAmount = placeOrderResp.getPayableAmount();
			//订单支付
			TradingCallService.payOrder(userId, useAccountAmount, tradingId);
			TradingSyncService.getSyncResult(orderId);
			//接单
			TradingCallService.sellerAcceptOrder(sellerId, orderId);
			TradingSyncService.getSyncResult(orderId);
			//发货
			TradingCallService.delivery(sellerId, orderId, LogisticsTypeEnum.OVERSEAS_DELIVERY, 1);
			TradingSyncService.getSyncResult(orderId);

			//自动确认收货时间操作表（auto_receive_opt） 
			AutoReceiveOptPo record = new AutoReceiveOptPo();
			record.setOrderId(orderId);
			record.setExpectReceiveTime(DateTime.now().plusDays(-1).toDate());

			//修改预期自动确认收货时间为昨天
			orderShardingWapper.autoReceiveOptMapper
					.updateByPrimaryKeySelective(record);

			Logger.comment("前置数据准备结束");

			// 发送请求
			confirmreceivecall.setData("{}");
			confirmreceivecall.callService();

			Logger.verifyEquals("ok", confirmreceivecall.getReturnData(),
					"验证接口返回");

			Thread.sleep(20000);

			// 数据库验证
			Ts_ConfirmReceive.verifyOrderStatus(orderId, "自动确认收货", -1);

			// 订单表(order)
			OrderPo ymtOrders = orderShardingWapper
					.selectOrderbyOrderId(orderId);

			Logger.verifyEquals(10000, ymtOrders.getOrderStatusMemo(),
					"验证订单子状态");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_AutoConfirmReceive_003() {
		Logger.start(true, "分期乐订单自动确认收货失败");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
					.placeFenqileOrder(LogisticsTypeEnum.OVERSEAS_DELIVERY);

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();

			long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

			long userId = placeOrderResp.getUserId();

			long tradingId = placeOrderResp.getTradingId();

			BigDecimal useAccountAmount = placeOrderResp.getPayableAmount();
			//订单支付
			TradingCallService.payOrder(userId, useAccountAmount, tradingId);
			TradingSyncService.getSyncResult(orderId);
			//接单
			TradingCallService.sellerAcceptOrder(sellerId, orderId);
			TradingSyncService.getSyncResult(orderId);
			//发货
			TradingCallService.delivery(sellerId, orderId, LogisticsTypeEnum.OVERSEAS_DELIVERY, 1);
			TradingSyncService.getSyncResult(orderId);

			//自动确认收货时间操作表（auto_receive_opt） 
			AutoReceiveOptPo record = new AutoReceiveOptPo();
			record.setOrderId(orderId);
			record.setExpectReceiveTime(DateTime.now().plusDays(-1).toDate());

			//修改预期自动确认收货时间为昨天
			orderShardingWapper.autoReceiveOptMapper
					.updateByPrimaryKeySelective(record);

			Logger.comment("前置数据准备结束");

			// 发送请求
			confirmreceivecall.setData("{}");
			confirmreceivecall.callService();

			Logger.verifyEquals("ok", confirmreceivecall.getReturnData(),
					"验证接口返回");

			Thread.sleep(10000);

			// 订单表(order)
			OrderPo ymtOrders = orderShardingWapper
					.selectOrderbyOrderId(orderId);

			// 码头自动确认收货任务无法确认
			Logger.verifyEquals(3, ymtOrders.getOrderStatus(),
					"验证订单状态");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_AutoConfirmReceive_004() {
		Logger.start(true, "订单下的所有商品退货退款成功，自动确认收货成功");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
					.placeOrderWithLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY);

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			Order order = placeOrderResp.getOrderList().get(0);

			long sellerId = placeOrderResp.getOrderList().get(0).getSellerId();

			Long userId = placeOrderResp.getUserId();

			long tradingId = placeOrderResp.getTradingId();

			Long thirdTradingId = TradingCallService.payOrder(userId,
					BigDecimal.ZERO, tradingId, "13");
			
			// 支付网关支付回调
			PayGateWayCallService.notifyCall("13", thirdTradingId.toString(),
					placeOrderResp.getPayableAmount().subtract(BigDecimal.ZERO)
							.toString(), userId.intValue());

			Thread.sleep(5000);

			TradingSyncService.getSyncResult(orderId);
			
			//接单
			TradingCallService.sellerAcceptOrder(sellerId, orderId);
			TradingSyncService.getSyncResult(orderId);
			
			//发货
			TradingCallService.delivery(sellerId, orderId, LogisticsTypeEnum.OVERSEAS_DELIVERY, 1);
			TradingSyncService.getSyncResult(orderId);
			
			TradingCallService.confirmReceive(userId, orderId);
			
			//自动确认收货时间操作表（auto_receive_opt） 
			AutoReceiveOptPo record = new AutoReceiveOptPo();
			record.setOrderId(orderId);
			record.setExpectReceiveTime(DateTime.now().plusDays(-1).toDate());

			//修改预期自动确认收货时间为昨天
			orderShardingWapper.autoReceiveOptMapper
					.updateByPrimaryKeySelective(record);
			
			ApplyRefundReq applyRefundReq = RefundService.applyRefund(order);

			salesrefundsuccessReq.setOrderId(orderId);

			int i = 0;
			
			for (SalesRefundInfoVo salesRefundInfoVo : applyRefundReq
					.getSalesRefundInfoList()) {

				salesrefundsuccessReq.setRefundBillNo(salesRefundInfoVo
						.getRefundBillNo());
				salesrefundsuccessCall.setData(salesrefundsuccessReq);

				Logger.comment(String.format("orderid: %s 第 %s 个商品 退款执行",
						orderId, i + 1));

				salesrefundsuccessCall.callService();

				Logger.verifyEquals("true",
						salesrefundsuccessCall.getString("success"),
						"验证退货退款成功返回");
				i++;
			}
			
			PayGateWayCallService.refundNotifyCall("13",
					thirdTradingId.toString(), userId);

			Logger.comment("前置数据准备结束");

			// 发送请求
			confirmreceivecall.setData("{}");
			confirmreceivecall.callService();

			Logger.verifyEquals("ok", confirmreceivecall.getReturnData(),
					"验证接口返回");

			Thread.sleep(20000);

			AutoReceiveOptPo autoReceiveOptPo = orderShardingWapper
					.selectAutoReceiveOptByOrderId(orderId);

			Logger.verifyEquals(true, autoReceiveOptPo.getFinish(), "验证数据库finish");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
}
